<?php
/**
 * Here is your custom functions.
 */
if (!function_exists('write_log')) {
    function write_log($msg, $extend = [], $level = 'error', $channel = 'api')
    {
        $requestParams = [];
        $requestInfo = [];
        if (!empty(request())){
            $method = request()->method();
            $requestInfo = [
                'ip' => request()->getRealIp(),
                'method' => $method,
                'uri' => ltrim(request()->fullUrl(),'/'),
                'time' => \Carbon\Carbon::now()->toDateTimeString(),
            ];
            $method = strtolower($method);
            $requestParams = in_array($method,['get','post']) ? request()->{$method}() : request()->all();
        }

        $logInfo = json_encode([
            'msg' => $msg,
            'extend' => $extend,
            'params' => $requestParams,
            'requestInfo' => $requestInfo,
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        // LOG_LEVEL_STATUS如下:
        $levelConst = [
            'debug' => 100,
            'info'  => 200,
            'warning' => 300,
            'error' => 400,
            'critical' => 500,
            'alert' => 550,
            'emergency' => 600
        ];
        \support\Log::channel($channel)->addRecord($levelConst[$level],$logInfo);
    }
}

if (!function_exists('load_service')) {
    /**
     * 按需注册 service
     * @param array $names 例如 ['test', 'user']
     */
    function load_service(array $names)
    {
        foreach ($names as $name) {
            $serviceClass = "app\\service\\" . ucfirst($name) . "Service";
            $logicClass = "app\\logic\\" . ucfirst($name) . "Logic";
            if (class_exists($serviceClass) && class_exists($logicClass)) {
                $serviceClass::register(new $logicClass());
            }
        }
    }
}

if (!function_exists('validate_request')) {
    /**
     * 动态调用 Request 验证类
     * @param string $requestClass
     * @param array $input
     * @param string $action
     * @return array
     */
    function validate_request(string $requestClass, array $input, string $action = ''): array
    {
        if (!$action) {
            // 自动获取调用者方法名
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
            // trace[1] 是 validate_request 的调用者
            if (isset($trace[1]['function'])) {
                $action = ucfirst($trace[1]['function']);
            }
        }
        if ($action) {
            $input['_action'] = $action;
        }
        $instance = new $requestClass($input);
        return $instance->validated();
    }
}

if (!function_exists('exp_abort')) {
    function exp_abort(string $msg = '')
    {
        throw new \app\exception\ExpressException($msg);
    }
}

if (! function_exists('hooks_action')) {
    function hooks_action(string $key, array $params, int | string $region = '',  bool $isNormal = true): void
    {
        $service = new \app\hooks\HookManager($region, $key, $params, $isNormal);
        $service->executeHooks();
    }
}